//
// Created by jie.jiang on 2022/10/20.
//
#include "command.h"
#include "main.h"
#include "usart.h"
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include "FOC.h"
#include "gui.h"

uint8_t usartRxDmaBuffer[USART_RX_DMA_BUFFER_SIZE]={0};
uint8_t dmaIdleFlag=0;
uint8_t dmaRxSize=0;
void HAL_UARTEx_RxEventCallback(UART_HandleTypeDef *huart, uint16_t Size){
  if (huart->ReceptionType==HAL_UART_RECEPTION_STANDARD){
    dmaIdleFlag=1;
    dmaRxSize=Size;
  }
}

void commandInit(void){
  HAL_UARTEx_ReceiveToIdle_DMA(&huart1,usartRxDmaBuffer,USART_RX_DMA_BUFFER_SIZE);
  dmaRxSize=0;
  dmaIdleFlag=0;
}
char* readStr(uint8_t len){
  if (len==0)return 0;
  char* str= malloc(len);
  for (int i = 0; i < len; i++) {
    *(str+i)=usartRxDmaBuffer[i];
  }
  return str;
}

void commandAnl(void){
  if (dmaIdleFlag){
    dmaIdleFlag=0;
    //printf("rec idle flag\n");
    char *cmd=readStr(dmaRxSize);
    char *buf= strtok(cmd,":");
    while (buf!=NULL){
      buf= strtok(NULL,":");
    }
    if (!strncmp(cmd,"mode",3)){ /// mode
      mode = atoi(strtok(cmd+5," "));
      printf("mode:%d\n",mode);
    } else if (!strncmp(cmd,"vel",3)){
      float param= atof(strtok(cmd+4," "));
      target_velocity=param;
      printf("vel:%.2f\n",target_velocity);
    } else if (!strncmp(cmd,"pos",3)){
      float param= atof(strtok(cmd+4," "));
      target_angle=param;
      printf("pos:%.2f\n",target_angle);
      gui_draw_position_mode(target_angle, 0);
    }
    free(cmd);
    HAL_UARTEx_ReceiveToIdle_DMA(&huart1,usartRxDmaBuffer,USART_RX_DMA_BUFFER_SIZE);
  }
}